package com.nuoye.camera2studydemo;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

/**
 * 显示fragment的adapter
 */
public class ShowFragmentActivity extends AppCompatActivity {
    /**
     *
     * @param context
     * @param fragment
     */
    public static void open(Context context,String fragment){
        Intent intent = new Intent(context, ShowFragmentActivity.class);
        intent.putExtra("fragment",fragment);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_fragment);
        String fragment= getIntent().getStringExtra("fragment");
        showFragment(fragment,getSupportFragmentManager(),R.id.showFragment);
    }
    public  void showFragment(String className, FragmentManager fragmentManager, int id) {
        Fragment fragment = null;
        try {

            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            //隐藏所有的那个啥。
            for (Fragment fra : fragmentManager.getFragments()) {
                fragmentTransaction.hide(fra);
            }
            Fragment fragmentByTag = fragmentManager.findFragmentByTag(className);
            if (fragmentByTag != null) {
                fragmentTransaction.show(fragmentByTag);
            } else {
                fragment = (Fragment) Class.forName(className).newInstance();
                fragmentTransaction.add(id, fragment, className);
            }
            //添加到返回栈中
            //  fragmentTransaction.addToBackStack(className);
            fragmentTransaction.commitAllowingStateLoss();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}